<template>
	<view>
		<view class="content" @touchstart="hideDrawer">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation"
				:scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory"
				upper-threshold="50">
				<!-- 加载历史数据waitingUI -->
				<view style="height: 1rpx;" v-show="scrollAnimation"></view>
				<view class="loading" v-show="!scrollAnimation">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<view class="card-container" v-show="taskinfo.orderId&&jmpType==0">
					<view class="card-container-box">
						<view class="card-container-box-left">
							<view class="box-left-title">
								<view class="box-left-title-left">{{taskinfo.taskName}}</view>
								<view class="box-left-title-right">
									<text v-if="taskinfo.floorsstr===1">保底{{taskinfo.baoDi}}元/小时</text>
									<text v-else>{{taskinfo.gongJia}}{{taskinfo.danwei}}</text>
								</view>
							</view>
							<view class="box-left-title-des">
								<view class="box-left-title-des-left">
									<text style="padding-bottom: 15rpx;">工作时间</text>
									<text>工作地点</text>
								</view>
								<view class="box-left-title-des-right">
									<text style="padding-bottom: 15rpx;">{{taskinfo.taskTime}}</text>
									<text class="des-right-text">{{taskinfo.taskAddress}}</text>
								</view>
							</view>
						</view>
						<view class="card-container-box-right">
							<view class="box-right-top">
								<image :src="imgPath +toUser.userAvatar" mode="aspectFill"></image>
							</view>
							<view class="box-right-bottom">
								<text>诚信值：{{taskinfo.integrity}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="tips-box" v-if="jmpType==1" style="margin-top: 60rpx;">温馨提示：为保护您的权益，请您尽量在平台内沟通，警惕招聘骗局！
				</view>
				<view class="tips-box" v-else>温馨提示：为保护您的权益，请您尽量在平台内沟通，警惕招聘骗局！</view>
				<view :key="msgRangeKey">
					<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.createTime">
						<!-- 系统消息 -->
						<block v-if="row.type=='system'">
							<view class="system">
								<!-- 文字消息 -->
								<view v-if="row.msgType==1" class="text">
									{{row.msg}}
								</view>
							</view>
						</block>
						<!-- 用户消息 -->
						<block v-else>
							<!-- 自己发出的消息 -->
							<view class="my" v-if="row.fromId == myuid">
								<!-- 左-消息 -->
								<view class="left">
									<!-- 文字消息 -->
									<view v-if="row.msgType==1" class="bubble">
										<!--                    <rich-text :nodes="row.msg"></rich-text>-->
										<rich-text :nodes="row.msg"></rich-text>
									</view>
									<!-- 图片消息 -->
									<view v-if="row.msgType==4" class="bubble img" @click="showPic(row.msg)">
										<image :src="imgPath + row.msg" :style="{'width': '100px'}" mode="widthFix">
										</image>
									</view>
								</view>
								<!-- 右-头像 -->
								<view class="right">
									<image :src="imgPath + myinfo.user.avatar"></image>
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<!-- v-if="row.msg.userinfo.uid!=myuid" -->
							<view class="other" v-if="row.fromId == toUser.userId">
								<!-- 左-头像 -->
								<view class="left">
									<image :src="imgPath + toUser.userAvatar"></image>
								</view>
								<!-- 右-用户名称-时间-消息 -->
								<view class="right">
									<view class="username">
										<view class="name">{{toUser.userName}}</view>
										<view class="time">{{$u.timeFrom(row.createTime)}}</view>
									</view>
									<!-- 文字消息 -->
									<view v-if="row.msgType==1" class="bubble">
										<rich-text :nodes="row.msg"></rich-text>
									</view>
									<!-- 图片消息 -->
									<view v-if="row.msgType==4" class="bubble img" @click="showPic(row.msg)">
										<image :src="imgPath + row.msg" :style="{'width': '100px'}" mode="widthFix">
										</image>
									</view>
								</view>
							</view>
						</block>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 更多功能 相册-拍照-红包 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @click="chooseImage">
						<view class="icon tupian2"></view>
					</view>
					<view class="box" @click="camera">
						<view class="icon paizhao"></view>
					</view>
					<view class="box" @click="weizhi">
						<image style="font-size:16px;width: 32px; height: 32px;" src="../../static/img/more/weizhi.png">
						</image>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部输入栏 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<view class="more" @click="showMore" v-if="isDisableL=='true'">
				<view class="icon1 add1">
					<image src="../../static/icon1/chat.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="more" v-if="isDisableL=='false'">
				<view class="icon1 add1">
					<image src="../../static/icon1/chat2.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="textbox" v-if="isDisableL=='false'">
				<view class="text-mode">
					<view class="box">
						<textarea disabled placeholder="当前状态无法使用该功能，如有疑问联系在线" auto-height="true" cursor-spacing="200"
							v-model="textMsg" placeholder-style="color:#ccc"
							style="font-size: 24rpx;color: #f5f5f5;text-align: center;" />
					</view>
				</view>
			</view>
			<view class="textbox" v-if="isDisableL=='true'">
				<view class="text-mode">
					<view class="box">
						<textarea auto-height="true" cursor-spacing="200" v-model="textMsg" @focus="textareaFocus" />
					</view>
				</view>
			</view>
			<view class="send" v-if="isDisableL=='false'">
				<view class="btn" style="background:#f2f2f2">发送</view>
			</view>
			<view class="send" @click="sendText" v-if="isDisableL=='true'">
				<view class="btn">发送</view>
			</view>
		</view>
	</view>
</template>
<script>
	import sqlite from '@/libs/sqlite/chatSqlite.js'
	export default {
		components: {},
		data() {
			return {
				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: true,
				scrollTop: 999999999,
				scrollToView: '',
				msgList: [], // 消息记录
				msgImgList: [], // 所有图片
				myinfo: uni.getStorageSync('userInfo'), // 自己的信息
				myuid: uni.getStorageSync('userId'), // 自己的uid
				toUser: {}, // 对方的信息
				taskinfo: { // 任务信息
					orderId: null,
					taskTime: null,
					taskName: null,
					taskAddress: null,
					integrity: null,
					gongJia: null,
					danwei: null,
					floorsstr: null,
					baoDi: null
				},
				// 抽屉参数
				popupLayerClass: '',
				jmpType: 0,
				// more参数
				testdata: "",
				hideMore: true,
				imgPath: '',
				uploadToken: null, // 七牛云token
				msgRangeKey: (Math.random() * 1000000000).toFixed(0),
				isFirstSend: true, // 是否首次发送
				isSender: false, // 是否主动从任务发起聊天者,
				isDisableL: 'false'
			};
		},
		onLoad(option) {
			console.log(option.stu)
			this.isDisableL = option.stu ? option.stu : 'false'
			console.log(this.isDisableL)
			this.jmpType = option.jmpType ? option.jmpType : 0
			this.toUser = JSON.parse(option.form)
			if (option.taskinfo) {
				this.isSender = true
				this.taskinfo = JSON.parse(option.taskinfo)
			}
			this.imgPath = uni.getStorageSync('imgPath')
			uni.setNavigationBarTitle({
				title: this.toUser.userName
			})
			this.initMsgList();
			this.getUploadToken()
			this.getLastTask()
			uni.$on('newMsg', this.getNewMsg)
		},
		onUnload() {
			uni.$off('newMsg', this.getNewMsg)
		},
		onShow() {
			let that = this
			that.$nextTick(function() {
				setTimeout(() => {
					that.scrollTop = 999999999;
				}, 300)
			})
			uni.$on('updateData', function(data) {
				that.testdata = '我的位置：' + data
			})
			if (that.testdata !== "") {
				that.hideDrawer();
				that.sendMsg(that.testdata, 1);
			}
			this.readMsg()
		},
		methods: {
			getNewMsg(newMsg) {
				if (newMsg.msgType === 6) {
					this.taskinfo = JSON.parse(newMsg.msg)
				} else {
					this.msgList.push(newMsg)
					this.msgRangeKey = (Math.random() * 1000000000).toFixed(0)
				}
				this.readMsg()
				this.$nextTick(function() {
					// 滚动到底
					// this.scrollTop = 999999999;
					this.scrollToView = 'msg' + newMsg.createTime
				})
			},
			readMsg() {
				sqlite.readMsg({
					fromId: this.toUser.userId
				}).then(res => {
					console.log('已读消息成功')
				}).catch(e => {
					console.log('已读消息失败', e)
				})
			},
			// 发送消息
			sendMsg(content, type) {
				const msgbody = {
					createTime: new Date().getTime(),
					fromId: this.myuid,
					toId: this.toUser.userId,
					msg: content,
					msgType: type
				}
				// 发送消息
				uni.sendSocketMessage({
					data: JSON.stringify(msgbody)
				});
				sqlite.insertMuser({
					userId: msgbody.toId
				}).then(() => {
					sqlite.insertMsg(msgbody, 1)
				})
				this.screenMsg(msgbody);
				this.autoSendCard()
				setTimeout(() => {
					this.testdata = ""
					// this.scrollTop = 999999999;
				}, 300)
			},
			// 发送任务卡片
			autoSendCard() {
				if (this.isSender && this.isFirstSend) {
					this.isFirstSend = false
					const msgbody = {
						createTime: new Date().getTime(),
						fromId: this.myuid,
						toId: this.toUser.userId,
						msg: JSON.stringify(this.taskinfo),
						msgType: 6
					}
					uni.sendSocketMessage({
						data: JSON.stringify(msgbody)
					});
					sqlite.insertMsg(msgbody, 1)
				}
			},
			// 发送文字消息
			sendText() {
				this.hideDrawer(); //隐藏抽屉
				if (!this.textMsg) {
					return;
				}
				this.sendMsg(this.textMsg, 1);
				this.textMsg = ''; //清空输入框
				setTimeout(() => {
					// this.scrollTop = 99999999;
				}, 300)
			},
			// 接受消息(筛选处理)
			screenMsg(msg) {
				switch (msg.msgType) {
					case 1:
						this.addTextMsg(msg);
						break;
					case 4:
						this.addImgMsg(msg);
						break;
				}
				this.$nextTick(function() {
					this.msgRangeKey = (Math.random() * 1000000000).toFixed(0)
					// 滚动到底
					this.scrollToView = 'msg' + msg.createTime
				});
			},
			//触发滑动到顶部(加载历史信息记录)
			loadHistory(e) {
				if (this.isHistoryLoading) {
					return;
				}
				this.isHistoryLoading = true; //参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false; //关闭滑动动画
				let Viewid = this.msgList[0].createTime; //记住第一个信息ID
				// 消息列表
				this.getMsgList()
				//这段代码很重要，不然每次加载历史数据都会跳到顶部
				this.$nextTick(function() {
					this.scrollToView = 'msg' + Viewid; //跳转上次的第一行信息位置
					this.$nextTick(function() {
						this.scrollAnimation = true; //恢复滚动动画
					});
				});
				this.isHistoryLoading = false;
			},
			// 加载初始页面消息
			initMsgList() {
				this.getMsgList()
				// 滚动到底部
				this.$nextTick(function() {
					//进入页面滚动到底部
					this.scrollTop = 9999;
					this.$nextTick(function() {
						this.scrollAnimation = true;
					});
				});
			},
			getLastTask() {
				const queryMap = {
					fromId: this.toUser.userId,
					toId: this.myuid,
					msgType: 6
				}
				sqlite.selectLastMsg(queryMap).then(dbobj => {
					console.log('dbinfo------------', dbobj)
					if (dbobj && dbobj.length > 0) {
						this.taskinfo = JSON.parse(dbobj[0].msg)
					}
				}).catch(e => {
					console.log('查询出错', e)
				})
			},
			getMsgList() {
				// 消息列表
				const queryMap = {
					fromId: this.toUser.userId,
					toId: this.myuid
				}
				if (this.msgList && this.msgList.length > 0) {
					let firstmsg = this.msgList[0]
					if (firstmsg.id) {
						queryMap.id = firstmsg.id
					} else {
						queryMap.createTime = firstmsg.createTime
					}
				}
				sqlite.pageList(queryMap).then(dbobj => {
					console.log('dbinfo------------', dbobj)
					if (dbobj && dbobj.length > 0) {
						// dbobj = dbobj.reverse()
						dbobj.forEach(dbobjItem => {
							this.msgList.unshift(dbobjItem)
						})
					}
				}).catch(e => {
					console.log('查询出错', e)
				})
			},
			//更多功能(点击+弹出)
			showMore() {
				this.isVoice = false;
				if (this.hideMore) {
					this.hideMore = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer() {
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer() {
				this.popupLayerClass = '';
				setTimeout(() => {
					this.hideMore = true;
				}, 150);
			},
			// 选择图片发送
			chooseImage() {
				this.getImage('album');
			},
			//拍照发送
			camera() {
				this.getImage('camera');
			},
			//选照片 or 拍照
			getImage(type) {
				this.hideDrawer();
				uni.chooseImage({
					count: 1,
					sourceType: [type],
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						// TODO: 这里应该先将图片显示上去 在加一个加载框 完成后去除
						this.uploadImgs(res.tempFilePaths[0]).then(key => {
							// uni.downloadFile({
							// 	url: this.imgPath + key,
							// 	success: (res) => {
							// 		if (res.statusCode === 200) {
							// 			callBack(res.tempFilePath)
							// 		}
							// 	},
							// 	fail: (err) => {
							// 		console.error(err)
							// 	}
							// });
							this.sendMsg(key, 4)
						})
					}
				});
			},
			// 获取七牛上传TOKEN
			getUploadToken() {
				this.$fetch(this.$api.get_qiniu_token, {}, 'POST').then(res => {
					this.uploadToken = res.msg
				})
			},
			// 上传图片至七牛
			async uploadImgs(file) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$api.uploadPic,
						name: 'file',
						filePath: file,
						formData: {
							key: `msgfile_${this.$u.guid()}_${Date.now()}`,
							token: this.uploadToken
						},
						success: ({
							data
						}) => {
							console.log('文件上传完成---', data)
							resolve(JSON.parse(data)?.key)
						}
					})
				})
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
					// this.hideDrawer();
				}
				// this.hideDrawer()
			},
			// 添加文字消息到列表
			addTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg) {
				// TODO: 存放图片到仓库 后续显示使用仓库
				// uni.setStorageSync(msg.msg, )
				this.msgImgList.push(msg.msg);
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg) {
				this.msgList.push(msg);
			},
			weizhi() {
				uni.navigateTo({
					url: '/pages/chooseLocation/chooseLocation?type=map'
				})
			},
			userinfo() {},
			// 预览图片
			showPic(msg) {
				console.log(this.imgPath + msg)
				uni.previewImage({
					current: 0,
					urls: [this.imgPath + msg]
				});
			},
			discard() {
				return;
			}
		}
	}
</script>
<style lang="scss">
	@import "@/static/hecss/style.scss";

	.tips-box {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 22rpx;
		color: #999;
	}

	.card-container {
		width: 90%;
		margin: 0 auto;
		height: 200rpx;
		margin-top: 60rpx;
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		.card-container-box {
			width: 94%;
			height: 72%;
			// border: 1px solid;
			display: flex;
			justify-content: center;
			align-items: center;

			.card-container-box-left {
				flex: 1;
				height: 100%;
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				flex-direction: column;

				// border: 1px solid red;
				.box-left-title {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					font-size: 30rpx;
					font-weight: 600;

					// padding-bottom: 20rpx;
					.box-left-title-left {
						width: 188rpx;
						// border: 1px solid;
						text-overflow: ellipsis;
						overflow: hidden;
						white-space: nowrap;
						text-align: left;
						// padding-right: 20rpx;
					}

					.box-left-title-right {
						color: #F39B19;
						padding-left: 20rpx;
					}
				}

				.box-left-title-des {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					// border: 1px solid;
					font-size: 22rpx;
					color: #ccc;

					.box-left-title-des-left {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						flex-direction: column;
						padding-right: 20rpx;
					}

					.box-left-title-des-right {
						display: flex;
						justify-content: flex-start;
						align-items: flex-start;
						flex-direction: column;

						.des-right-text {
							width: 300rpx;
							// border: 1px solid;
							text-overflow: ellipsis;
							overflow: hidden;
							white-space: nowrap;
							text-align: left;
						}
					}
				}
			}

			.card-container-box-right {
				width: 180rpx;
				height: 100%;
				// border: 1px solid;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.box-right-top {
					width: 94rpx;
					height: 94rpx;
					// border: 1px solid;
					border-radius: 50%;

					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.box-right-bottom {
					margin-top: -10rpx;
					width: 160rpx;
					height: 48rpx;
					z-index: 999999999;
					background: #FCC928;
					// border-bottom-left-radius: 10rpx;
					border-bottom-right-radius: 18rpx;
					border-top-left-radius: 18rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 22rpx;
				}
			}
		}
	}
</style>
